package cc.fs.androidcode.ui.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import cc.fs.androidcode.R;
import cc.fs.androidcode.utils.mqtt.MqttClient;


/**
 * Created by fostion on 12/25/15.
 *
 * android mqtt 使用demo
 */
public class MqttActivity extends AppCompatActivity {

    Button startBtn;
    Button publishBtn;
    Button bookBtn;
    MqttClient client;

    StringBuilder stringBuilder;
    TextView textView;

    public void e(String msg) {
        Log.e("----------------", msg);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_mqtt);

        startBtn = (Button) findViewById(R.id.startBtn);
        publishBtn = (Button) findViewById(R.id.publishBtn);
        bookBtn = (Button) findViewById(R.id.bookBtn);
        textView = (TextView) findViewById(R.id.msgBox);

        stringBuilder = new StringBuilder();


        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MqttActivity.this, "开始mqtt服务了", Toast.LENGTH_SHORT).show();
                client = MqttClient.getInstance();
                client.setResponse(new MqttClient.Response<String>() {
                    @Override
                    public void run(final String param) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stringBuilder.append(param+"\n");
                                textView.setText(stringBuilder.toString());
                            }
                        });
                        e("订阅返回来的消息" + param);
                    }
                });
            }
        });

        publishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                client.publish("fostion/test", "hello this is test", new MqttClient.Response<Boolean>() {
                    @Override
                    public void run(Boolean param) {
                        if (param) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MqttActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        });
    }

}
